﻿#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_

/* thread pool */

#include <string>
#include <atomic>
#include <functional>

typedef struct event_s
{
    void* data;

    unsigned int    active : 1;
    unsigned int    complete : 1;

    void (*handler)(struct event_s* ev);

    event_s()
    {
        data = 0;

        active = 0;
        complete = 0;

        handler = 0;
    }
}event_t;

struct thread_task_s {
    struct thread_task_s*                    next;

    void*                                    ctx;                                            /* 参数 */
    std::function<void(void*)>  handler;

    unsigned int                             id;
    event_t                                  ev;
};
typedef struct thread_task_s thread_task_t;

typedef struct {
    thread_task_t* first;
    thread_task_t** last;
} thread_pool_queue_t;

struct thread_pool_s 
{
    pthread_mutex_t        m_mutex;
    pthread_cond_t         m_cond;

    thread_pool_queue_t   m_queue;
    int                   m_waiting;

    int                   m_add_thread;
    int                   m_sub_thread;

    int                   m_idle_time;

    std::string           m_name;

    std::atomic<int>      m_threads;
    std::atomic<int>      m_max_threads;

    int                   m_max_queue;
};
typedef struct thread_pool_s  thread_pool_t;

#define ngx_thread_pool_queue_init(q)                                         \
    (q)->first = NULL;                                                        \
    (q)->last = &(q)->first

void* thread_pool_manage(void* data);
void* thread_pool_cycle(void* data);

void thread_exit_handler(void* data);

int thread_pool_init(char* errStr, thread_pool_t* tp);
int thread_pool_destroy(char* errStr, thread_pool_t* tp);

int thread_task_post(char* errStr, thread_pool_t* tp, thread_task_t* task);

int thread_pool_handler();

#endif /* _THREAD_POOL_H_ */